package com.bosssoft.trainee.nontax.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.bosssoft.trainee.nontax.common.Result;
import com.bosssoft.trainee.nontax.entity.po.User;
import com.bosssoft.trainee.nontax.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService userService;

    @PostMapping("/login")
    public Result<?> login(@RequestBody User userParam) { return userService.login(userParam); }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) { return userService.register(user); }

    @PostMapping
    public Result<?> save(@RequestBody User user) {
        Result result = getUser();
        if (result.getCode().equals("0")) {
            return userService.saveUser(user);
        } else {
            logger.error("UserController save - user did't login");
            return result;
        }
    }


    @PutMapping
    public Result<?> update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }

    @PutMapping("/pass")
    public Result<?> pass(@RequestBody Map<String, Object> map) {
        return userService.pass(map);
    }

    // 改变权限接口
    @PutMapping("/changeRole")
    public Result<?> changeRole(@RequestBody User user) {
        if (!existsUser(user)) return Result.error("-1", "该用户不存在！");
        userService.changeRole(user);
        // 获取当前登录用户的角色id列表
        Result result = getUser();
        if (result.getCode().equals("0")) {
            User currentUser = (User) result.getData();
            // 如果当前登录用户的角色列表包含需要修改的角色id，那么就重新登录
            if (user.getId().equals(currentUser.getId())) {
                return Result.success(true);
            } else {
                // 如果不包含，则返回false，不需要重新登录。
                return Result.success(false);
            }

        } else {
          return result;
        }


    }

    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        return userService.update(id);
    }

    @GetMapping("/ban")
    public Result<?> banByUsername(@RequestParam String username,
                                   @RequestParam Boolean available) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("available", available);
        userService.updateAvailable(map);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(userService.getById(id));
    }

    @GetMapping("/all")
    public Result<?> findAll() { return Result.success(userService.list()); }

    /**
     * 统计数据
     *
     * @return
     */
    @GetMapping("/count")
    public Result<?> count() {
        return userService.countAddress();
    }

    /**
     * 用户分页列表查询，包含书籍表的一对多查询
     *
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        return userService.findPage(pageNum, pageSize, search);
    }

    /**
     * Excel导出
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = CollUtil.newArrayList();

        List<User> all = userService.list();

        for (User user : all) {
            Map<String, Object> row1 = new LinkedHashMap<>();
            row1.put("用户名", user.getUsername());
            row1.put("昵称", user.getNickName());
            row1.put("年龄", user.getAge());
            row1.put("性别", user.getSex());
            row1.put("地址", user.getAddress());
            list.add(row1);
        }

        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }

    /**
     * Excel导入
     * 导入的模板可以使用 Excel导出的文件
     *
     * @param file Excel
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public Result<?> upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        List<List<Object>> lists = ExcelUtil.getReader(inputStream).read(1);
        List<User> saveList = new ArrayList<>();
        for (List<Object> row : lists) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setNickName(row.get(1).toString());
            user.setAge(Integer.valueOf(row.get(2).toString()));
            user.setSex(row.get(3).toString());
            user.setAddress(row.get(4).toString());
            saveList.add(user);
        }
        for (User user : saveList) {
            userService.save(user);
        }
        return Result.success();
    }

    private boolean existsUser(User user) {
        List<User> list = (List<User>) findAll().getData();
        for (User u : list) {
            if (u.getId().equals(user.getId())) {
                return true;
            }
        }
        return false;
    }

}
